package com.aiyige.page.my.message.notifymessage.commentmessage;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.Page;
import com.aiyige.model.message.entity.Message;
import com.aiyige.model.message.view.CommentContent;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.request.AddCommentRequest;
import com.aiyige.model.sns.Comment;
import com.aiyige.page.detail.DetailPage;
import com.aiyige.page.my.message.notifymessage.commentmessage.adapter.CommentMessageAdapter;
import com.aiyige.page.my.message.notifymessage.commentmessage.model.CommentMessage;
import com.aiyige.page.my.message.util.MessageUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.vondear.rxtools.RxKeyboardTool;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.kevin.floatingeditor.EditorCallback;
import cn.kevin.floatingeditor.EditorHolder;
import cn.kevin.floatingeditor.FloatEditorActivity;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Route(path = ARouterConfig.CommentMessagePage)
public class CommentMessagePage extends AppCompatActivity implements CommonDataView.RetrofitStub {
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    CommentMessageAdapter commentMessageAdapter;
    @BindView(R.id.inputCommentEt)
    EditText inputCommentEt;
    @BindView(R.id.inputPanel)
    FrameLayout inputPanel;
    //    CommentMessage targetCommentMessage;
    TrackEvent trackEvent = new TrackEvent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_comment_message);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.comment);
        commentMessageAdapter = new CommentMessageAdapter();
        commentMessageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CommentMessage commentMessage = commentMessageAdapter.getItem(position);
                Router.start(commentMessage.getRouter());
            }
        });
        commentMessageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.otherNameTv:
                    case R.id.otherHeadIv: {
                        CommentMessage commentMessage = commentMessageAdapter.getItem(position);
                        ARouter.getInstance()
                                .build(ARouterConfig.UserPage)
                                .withString("userId", commentMessage.getOtherId())
                                .navigation();

                        break;
                    }
                    case R.id.replyBtn: {
//                        CommentMessage commentMessage = commentMessageAdapter.getItem(position);
//                        targetCommentMessage = commentMessage;
//                        inputCommentEt.setHint(getString(R.string.reply) + " " + commentMessage.getOtherName() + ":");
//                        KeyboardUtil.showKeyboard(CommentMessagePage.this, inputCommentEt);
                        final CommentMessage commentMessage = commentMessageAdapter.getItem(position);
                        String hintString = getString(R.string.reply) + " " + commentMessage.getOtherName() + ":";
                        FloatEditorActivity.openEditor(CommentMessagePage.this, new EditorCallback() {
                                    @Override
                                    public void onCancel(String content) {
                                        FloatEditorActivity.setDefaultValue(content);
                                        RxKeyboardTool.hideSoftInput(CommentMessagePage.this);
                                    }

                                    @Override
                                    public void onSubmit(String content) {
                                        FloatEditorActivity.setDefaultValue(null);
                                        doComment(commentMessage, content);
                                    }

                                    @Override
                                    public void onAttached(ViewGroup rootView) {


                                    }
                                },
                                new EditorHolder(R.layout.fast_reply_floating_layout,
                                        R.id.tv_cancel, R.id.tv_submit, R.id.et_content), hintString, new InputFilter[]{new InputNumFilter(200, true)});
                        break;
                    }
                    default:
                        break;
                }
            }
        });
        cdv.config(commentMessageAdapter, this);
        cdv.getRecyclerView().setItemAnimator(null);
        cdv.doRefreshRequest();
//        containerLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                int heightDiff = containerLayout.getRootView().getHeight() - containerLayout.getHeight();
//                if (heightDiff > UIHelper.dip2px(200)) { // if more than 200 dp, it's probably a keyboard...
//                    inputPanel.setVisibility(View.VISIBLE);
//                } else {
//                    inputPanel.setVisibility(View.INVISIBLE);
//                }
//            }
//        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.titleBackBtn, R.id.sendCommentBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.sendCommentBtn:

                break;
        }
    }

    private void doComment(final CommentMessage targetCommentMessage, final String content) {

        Comment comment = new Comment();
        comment.setSubject(targetCommentMessage.getGoodsType());
        comment.setContent(content);
        comment.setOriginObjectId(targetCommentMessage.getGoodsId());
        comment.setObjectId(targetCommentMessage.getOtherCommentId());
        comment.setObjectType(Comment.comment);
        final LoadingDialog loadingDialog = LoadingDialog.newBuilder()
                .with(this)
                .show();
        AddCommentRequest.newBuilder()
                .comment(comment)
                .build()
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.code() != ResponseCode.CREATED) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            } else {
                                trackEvent.sendEvent(CommentMessagePage.this, TrackEvent.MY_COMMENT_MSG_REPLY_SUCCESS, TrackEvent.MY_COMMENT_MSG_REPLY_SUCCESS_LABEL);
                                if (AccountUtil.getCurrentUser().getId().equals(targetCommentMessage.getOtherId())) {
                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                    Comment respComment = JSON.parseObject(json, Comment.class);
                                    CommentMessage respCommentMessage = CommentMessage.newBuilder()
                                            .otherAvatar(AccountUtil.getCurrentUser().getAvatar())
                                            .otherId(AccountUtil.getCurrentUser().getId())
                                            .otherName(AccountUtil.getCurrentUser().getAccount())
                                            .goodsId(targetCommentMessage.getGoodsId())
                                            .goodsType(targetCommentMessage.getGoodsType())
                                            .otherTime(System.currentTimeMillis())
                                            .mediaReleaseDate(targetCommentMessage.getMediaReleaseDate())
                                            .cover(targetCommentMessage.getCover())
                                            .targetType(MessageUtil.TARGET_TYPE_COMMENT)
                                            .mediaTitle(targetCommentMessage.getMediaTitle())
                                            .myComment(targetCommentMessage.getOtherComment())
                                            .myName(targetCommentMessage.getOtherName())
                                            .router(targetCommentMessage.getRouter())
                                            .otherComment(respComment.getContent())
                                            .otherCommentId(respComment.getId())
                                            .build();
                                    commentMessageAdapter.addData(0, respCommentMessage);
                                    cdv.backToTop(true);
                                }
                                ToastX.show(R.string.reply_success);
                            }
                            loadingDialog.dismiss();
                        } catch (Exception e) {
                            onFailure(call, e);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        loadingDialog.dismiss();
                        ToastX.show(t.getMessage());
                    }
                });
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return ApiManager.getService().message(Message.TYPE_COMMENT, 15, currentPage);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Message> messageList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                messageList.addAll(JSON.parseArray(page.getContent(), Message.class));
            }
            for (Message message : messageList) {
                CommentContent record = null;
                try {
                    record = message.getContent().toJavaObject(CommentContent.class);
                } catch (Exception e) {

                }
                if (record == null || record.getComment() == null) {
                    continue;
                }
                int targetType;
                if (record.getComment().getOriginComment() != null) {
                    targetType = MessageUtil.TARGET_TYPE_COMMENT;
                } else {
                    switch (record.getMoment().getSubject()) {
                        case Moment.SUBJECT_ARTICLE:
                            targetType = MessageUtil.TARGET_TYPE_INFO;
                            break;
                        case Moment.SUBJECT_VIDEO:
                            targetType = MessageUtil.TARGET_TYPE_VIDEO;
                            break;
                        case Moment.SUBJECT_PHOTO:
                            targetType = MessageUtil.TARGET_TYPE_PHOTO;
                            break;
                        case Moment.SUBJECT_VIDEO_COURSE:
                            targetType = MessageUtil.TARGET_TYPE_LEARN_VIDEO;
                            break;
                        case Moment.SUBJECT_MAJOR_COURSE:
                            targetType = MessageUtil.TARGET_TYPE_MAJOR_COURSE;
                            break;
                        case Moment.SUBJECT_SPECIAL_TOPIC:
                            targetType = MessageUtil.TARGET_TYPE_SPECIAL_TOPIC;
                            break;
                        case Moment.SUBJECT_TRAINING_COURSE:
                            targetType = MessageUtil.TARGET_TYPE_TRAING_CARD;
                            break;
                        case Moment.SUBJECT_PRIVATE_COURSE:
                            targetType = MessageUtil.TARGET_TYPE_PERSONAL_TRAINER;
                            break;
                        default:
                            targetType = MessageUtil.TARGET_TYPE_COMMENT;
                            break;
                    }
                }
                String myComment = "";
                try {
                    myComment = record.getComment().getOriginComment().getContent();
                } catch (Exception e) {

                }
                String myName = "";
                try {
                    myName = record.getComment().getOriginComment().getUser();
                } catch (Exception e) {

                }

                resultList.add(CommentMessage.newBuilder()
                        .otherAvatar(record.getSender().getAvatar())
                        .otherId(record.getSender().getId())
                        .otherName(record.getSender().getName())
                        .goodsId(record.getMoment().getId())
                        .goodsType(record.getMoment().getSubject())
                        .otherTime(message.getCreateTime())
                        .mediaReleaseDate(record.getMoment().getCreateTime())
                        .cover(record.getMoment().getCover())
                        .targetType(targetType)
                        .mediaTitle(record.getMoment().getTitle())
                        .myComment(myComment)
                        .myName(myName)
                        .router(record.getMoment().getRouter())
                        .otherComment(record.getComment().getContent())
                        .otherCommentId(record.getComment().getId())
                        .build());
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }
}
